const dsteem = require('dsteem')

let opts = {}

//connect to community testnet
opts.addressPrefix = 'STX'
opts.chainId = '79276aea5d4877d9a25892eaa01b0adf019d3e5cb12a97478df3298ccdd01673'
//connect to server which is connected to the network/testnet
const client = new dsteem.Client('https://testnet.steem.vc', opts)

//connect to official testnet
//opts.addressPrefix = 'TST'
//opts.chainId = '46d82ab7d8db682eb1959aed0ada039a6d49afa1602491f93dde9cac3e8e6c32'
//connect to server which is connected to the network/testnet
//const client = new dsteem.Client('https://testnet.steemitdev.com', opts)


//connect to production server
//opts.addressPrefix = 'STM'
//opts.chainId = '0000000000000000000000000000000000000000000000000000000000000000'
//connect to server which is connected to the network/production
//const client = new dsteem.Client('https://api.steemit.com')

let privateKey = ''
let account = ''
let opType = ''
let op = {}
let stx
let expireTime = 60 * 1000 //1 min
let head_block_number = 0
let head_block_id = ''

async function main() {
    //get current state of network
    const props = await client.database.getDynamicGlobalProperties()
    //extract last/head block number
    head_block_number = props.head_block_number
    //extract block id
    head_block_id = props.head_block_id
}
//catch error messages
main().catch(console.error)

//account change selection function
window.accountChange = async() => {
    //get private key for selected account
    privateKey = dsteem.PrivateKey.fromString(document.getElementById("account").value)
    //get selected account name
    account = document.getElementById("account").selectedOptions[0].text
}

//operation type change selection function
window.opChange = async() => {
    //get operation type
    opType = document.getElementById("optype").value;
}

//generate transaction function
window.generateTx = () => {
    //check operation type
    if (opType=='vote') {
        //vote operation/transaction
        op = {
            ref_block_num: head_block_number, //reference head block number required by tapos (transaction as proof of stake)
            ref_block_prefix: Buffer.from(head_block_id, 'hex').readUInt32LE(4), //reference buffer of block id as prefix
            expiration: new Date(Date.now() + expireTime).toISOString().slice(0, -5), //set expiration time for transaction (+1 min)
            operations: [['vote', {
                voter: account,
                author: 'test',
                permlink: 'test',
                weight: 10000
            }]],//example of operation object for vote
            extensions: [],//extensions for this transaction
        }
        //set operation output
        document.getElementById("OpInput").innerHTML = JSON.stringify(op, undefined, 2)
    }
    if (opType=='follow') {
        //follow operation
        op = {
            ref_block_num: head_block_number,
            ref_block_prefix: Buffer.from(head_block_id, 'hex').readUInt32LE(4),
            expiration: new Date(Date.now() + expireTime).toISOString().slice(0, -5),
            operations: [['custom_json', {
                required_auths: [],
                required_posting_auths: [account],
                id: 'follow',
                json: '["follow",{"follower":"'+account+'","following":"test","what":["blog"]}]'
            }]], //example of custom_json for follow operation
            extensions: [],
        }
        document.getElementById("OpInput").innerHTML = JSON.stringify(op, undefined, 2)
           
    }
    if (opType=='reblog') {
        //reblog operation
        op = {
            ref_block_num: head_block_number,
            ref_block_prefix: Buffer.from(head_block_id, 'hex').readUInt32LE(4),
            expiration: new Date(Date.now() + expireTime).toISOString().slice(0, -5),
            operations: [['custom_json', {
                required_auths: [],
                required_posting_auths: [account],
                id: 'follow',
                json: '["reblog",{"account":"'+account+'","author":"test","permlink":"test"}]'
            }]], //example of custom_json for reblog operation
            extensions: [],
        }
        document.getElementById("OpInput").innerHTML = JSON.stringify(op, undefined, 2)
    }   
}

window.signTx = () => {
    //sign transaction/operations with user's privatekey
    stx = client.broadcast.sign(op, privateKey)
    //set output
    document.getElementById("TxOutput").innerHTML = JSON.stringify(stx, undefined, 2)
    console.log(stx)
}

window.verifyTx = async() => {
    //verify signed transaction authority
    const rv = await client.database.verifyAuthority(stx)
    //set checkmark or crossmark depending on outcome
    let node = document.getElementById('verifyBtn');
    rv?node.insertAdjacentHTML('afterend', '&nbsp;&#x2714;&nbsp;'):node.insertAdjacentHTML('afterend', '&nbsp;&#x2717;&nbsp;')
}

window.broadcastTx = async() => {
    //broadcast/send transaction to the network
    const res = await client.broadcast.send(stx)
    //set output
    document.getElementById("ResOutput").innerHTML = JSON.stringify(res, undefined, 2)
}